package com.spark.demoim.global

import android.app.ActivityManager
import android.content.Context
import android.util.Log
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMOptions
import com.spark.demoim.BuildConfig

/**
 * Created by lenovo on 2017/8/15.
 */
class IMHelper private constructor() {
    companion object {
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { IMHelper() }
    }

    /**
     * init
     */
    fun initial(builder: OptionBuilder) {
        // 多进程检查
        initService()
        initOptions(builder)
        // 打包混淆时，关闭 debug 模式，避免消耗不必要的资源
        //EMClient.getInstance().setDebugMode(true)
    }

    /**
     * 初始化环信 Option
     */
    fun initOptions(builder: OptionBuilder) {
        val options = EMOptions()
        options.acceptInvitationAlways = builder.acceptInvitaionAlways
        options.requireAck = builder.requireAck
        options.requireDeliveryAck = builder.requireDeliverAck
        options.gcmNumber = builder.gcmNumber
        options.setMipushConfig(builder.miPushConfig, builder.miPushConfig)
        if (builder.customAppKey.isNotEmpty()) options.appKey = builder.customAppKey
        options.allowChatroomOwnerLeave(builder.allowChatroomOwnerLeave)
        options.isAutoAcceptGroupInvitation = builder.isAutoAcceptGroupInvitation
        options.autoLogin = builder.autoLogin
    }

    /**
     * 初始化服务，避免多进程再次初始化
     */
    private fun initService() {
        val pid = android.os.Process.myPid()
        val processAppName = getAppName(pid)
        /* 如果 app 启用了远程的 service, 此 application 会被调用 2 次，
        * 为防止环信 SDK 被初始化 2 次，加此判断保证 SDK 被初始化 1 次
        * 默认的 app 会在以包名为默认的 process name 下运行，如果查到 process name 不是 app 的 process name就立即返回
        * */
        if (processAppName.isNullOrEmpty() and !(processAppName?.equals(App.appContext?.packageName, ignoreCase = true)!!)) {
            Log.e("IMHelper...", "enter the service process!")
            // 此 application::oncreate 是被 service 调用的，直接返回
            return
        }
    }

    /**
     * 获取 app name
     */
    private fun getAppName(PID: Int): String? {
        var processName: String? = null
        val am = App.appContext?.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (runningAppProcess in am.runningAppProcesses) {
            if (runningAppProcess.pid == PID) {
                processName = runningAppProcess.processName
                return processName
            }
        }
        return processName
    }

    /**
     * Options Builder 模式
     */
    class OptionBuilder {
        var acceptInvitaionAlways = false
        var requireAck = false
        var requireDeliverAck = false
        var allowChatroomOwnerLeave = false
        var isDeleteMsgAsExitGroup = false
        var isAutoAcceptGroupInvitation = false
        var customAppKey = ""
        var miPushConfig = ""
        var gcmNumber = ""
        var huaiweiPushAppId = ""
        var autoLogin = true
        /**
         * 添加好友是否需要验证
         */
        fun setAcceptInvitationAlways(accept: Boolean): OptionBuilder {
            this.acceptInvitaionAlways = accept
            return this
        }

        /**
         * 是否需要已读回执
         */
        fun setRequireAck(ack: Boolean): OptionBuilder {
            this.requireAck = ack
            return this
        }

        /**
         * 是否需要送达确认
         */
        fun setRequireDeliverAck(ack: Boolean): OptionBuilder {
            this.requireDeliverAck = ack
            return this
        }

        /**
         * 是否允许聊天室创建者离开
         */
        fun setAllowChatroomOwnerLeave(allow: Boolean): OptionBuilder {
            this.allowChatroomOwnerLeave = allow
            return this
        }

        /**
         * 离开群组时是否删除消息
         */
        fun setIsDeleteMsgAsExitGroup(delete: Boolean): OptionBuilder {
            this.isDeleteMsgAsExitGroup = delete
            return this
        }

        /**
         * 是否自动接受群组要求不需验证
         */
        fun setIsAutoAcceptGroupInvitation(auto: Boolean): OptionBuilder {
            this.isAutoAcceptGroupInvitation = auto
            return this
        }

        /**
         * 设置自定义 AppKey
         */
        fun setCustomAppkey(appKey: String): OptionBuilder {
            this.customAppKey = appKey
            return this
        }

        /**
         * 小米推送
         */
        fun setMiPushConfig(config: String): OptionBuilder {
            this.miPushConfig = config
            return this
        }

        /**
         * GCM 推送
         */
        fun setGCMNumber(number: String): OptionBuilder {
            this.gcmNumber = number
            return this
        }

        /**
         * 华为推送
         */
        fun setHuaweiPushAppId(id: String): OptionBuilder {
            this.huaiweiPushAppId = id
            return this
        }

        /**
         * 设置是否自动登陆
         */
        fun setAutoLogin(auto: Boolean): OptionBuilder {
            this.autoLogin = auto
            return this
        }

        fun build() {
            return instance.initial(this)
        }
    }

}